/*
Java board game library.
Copyright (C) 2011  Deepesh Garg

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
*/

package d.g.boardgames.chess;

import java.io.BufferedReader;
import java.io.InputStreamReader;

import d.g.boardgames.chess.ChessCellState.PieceColor;
import d.g.boardgames.chess.ChessCellState.PieceType;

public class TextUI {

	ChessBoard chessBoard = new ChessBoard();
	FENSerializer fenSerializer = new FENSerializer();
	CoordinateMoveParser coordinateMoveParser = new CoordinateMoveParser();
	
	public TextUI () {
		
	}
	
	public void start() {
		String input = "";
		while (!input.equals("exit")) {
			displayBoard(chessBoard);
			displayFEN(chessBoard);
			String fen = fenSerializer.getString(chessBoard);
			ChessBoard testBoard = fenSerializer.getBoard(fen);
			displayBoard(testBoard);
			displayFEN(testBoard);
			input = readLine();
			ChessMove move = coordinateMoveParser.parseMoveString(chessBoard, input);
			chessBoard = chessBoard.move(move);
		}
	}
	
	public void displayBoard(ChessBoard chessBoard) {
		for (int row = 0; row < 8; row++) {
			for (int col = 0; col < 8; col++) {
				String s = "   ";
				if (chessBoard.getCellState(row, col) != null) {
					switch (chessBoard.getCellState(row, col).pieceType) {
						case KING : s = "[k]"; break;
						case QUEEN : s = "[q]"; break;
						case ROOK : s = "[r]"; break;
						case BISHOP : s = "[b]"; break;
						case KNIGHT : s = "[n]"; break;
						case PAWN : s = "[p]"; break;
						default : s = "   ";
					}
					if (chessBoard.getCellState(row, col).pieceColor == PieceColor.WHITE) {
						s = s.toUpperCase();
					} else {
						s = s.toLowerCase();
					}
				}
				System.out.print(s);
			}
		}
	}
	
	public void displayFEN(ChessBoard chessBoard) {
		System.out.println (fenSerializer.getString(chessBoard));
	}
	
	public static void main (String argv[]) {
		TextUI tui = new TextUI();
		tui.start();
	}
	
	public String readLine () {
		try {
            BufferedReader reader = new BufferedReader(new
            		InputStreamReader(System.in));
            String input = reader.readLine() ;
            return input ;
		} catch (Exception e) {
			System.out.println ("Error reading input:" + e) ;
            return "" ;
		}
	}
}
